﻿Imports System.Security.Cryptography
Imports System.Text
Imports System.IO

'Encriptacion TripleDes
'http://www.dreamincode.net/forums/topic/171440-encrypting-xml/
Public Class CriptoTripleDESUtil
    Private Shared DES As New TripleDESCryptoServiceProvider

    'data: string to encrypt 
    Public Shared Function encryptToBytes(ByVal data As String, ByVal key As Byte()) As Byte()
        DES.Key = key
        DES.Mode = CipherMode.ECB
        Dim Buffer As Byte() = ASCIIEncoding.ASCII.GetBytes(data)
        Return DES.CreateEncryptor().TransformFinalBlock(Buffer, 0, Buffer.Length)
    End Function


    Public Shared Function encrypt(ByVal data As String, ByVal key As Byte()) As String
        Return Convert.ToBase64String(encryptToBytes(data, key))
    End Function

    'data: encrypted string
    Public Shared Function decrypt(ByVal data() As Byte, ByVal key As Byte()) As String
        Try
            DES.Key = key
            DES.Mode = CipherMode.ECB
            Dim Buffer As Byte() = data
            Return ASCIIEncoding.ASCII.GetString(DES.CreateDecryptor().TransformFinalBlock(Buffer, 0, Buffer.Length))
        Catch
            MessageBox.Show("Wrong Key Number, decryption not available!")
            Return Nothing
        End Try
    End Function

    Public Shared Function decrypt(ByVal data As String, ByVal key As Byte()) As String
        Return decrypt(Convert.FromBase64String(data), key)
    End Function
End Class
